package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"teatch/model/cache"
	"teatch/pkg"
	"time"

	"teatch/teacherrpc/internal/svc"
	"teatch/teacherrpc/teacherrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *teacherrpc.SendSmsRequest) (*teacherrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	count, _ := cache.Rdb.Get(l.ctx, "SendVer"+in.Account).Int64()

	if count >= 1 {
		return nil, fmt.Errorf("已经发送过了,请1分钟以后再试")
	}

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}

	if sms.Code != 2 {
		return nil, fmt.Errorf(sms.Msg)
	}

	cache.Rdb.Set(l.ctx, "SendKey"+in.Account, code, time.Minute*5)
	cache.Rdb.Incr(l.ctx, "SendVer"+in.Account)
	cache.Rdb.Expire(l.ctx, "SendVer"+in.Account, time.Minute*1)
	return &teacherrpc.SendSmsResponse{
		Code:  int64(sms.Code),
		Msg:   sms.Msg,
		Smsid: sms.Smsid,
	}, nil
}
